package com.zhangye.test.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * HTTP工具类
 * 
 */
public class HttpTookit {
	private static Log log = LogFactory.getLog(HttpTookit.class);
	private static String charset = "UTF-8";

	/**
	 * 
	 * @param url 请求的URL地址
	 * @param parameters
	 * @return
	 */
	public static String doGet(String url, Map<String, String> parameters) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		String urlString = "";
		if (parameters != null) {
			StringBuffer param = new StringBuffer();
			int i = 0;
			for (String key : parameters.keySet()) {
				if (i == 0)
					param.append("?");
				else
					param.append("&");
				param.append(key).append("=").append(parameters.get(key));
				i++;
			}
			urlString += param;
		}
		try {
			if (StringUtils.isNotBlank(urlString))
				// 对get请求参数做了http请求默认编码，好像没有任何问题，汉字编码后，就成�?式样的字符串
				method.setQueryString(URIUtil.encodeQuery(urlString));
			client.executeMethod(method);
			client.setTimeout(5000);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(method.getResponseBodyAsStream(),
								charset));
				String line;
				while ((line = reader.readLine()) != null) {
					response.append(line).append(
							System.getProperty("line.separator"));
				}
				reader.close();
			}
		} catch (URIException e) {
			log.error("执行HTTP Get请求时，编码查询字符串?" + urlString + "”发生异常！", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时，发生异常", e);
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}

	/**
	 * @param url 请求的URL地址
	 * @param parameters
	 * @return
	 */
	public static String doPost(String url, Map<String, String> parameters) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		// 设置Http Post数据

		if (parameters != null) {
			NameValuePair par[] = new NameValuePair[parameters.size()];
			int i = 0;
			for (Map.Entry<String, String> entry : parameters.entrySet()) {
				par[i] = new NameValuePair(entry.getKey(), entry.getValue());
				i++;
			}
			method.setRequestBody(par);
		}

		try {
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			client.executeMethod(method);
			client.setTimeout(5000);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(method.getResponseBodyAsStream(),
								charset));
				String line;
				while ((line = reader.readLine()) != null) {
					response.append(line).append(
							System.getProperty("line.separator"));
				}
				reader.close();
			}
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时，发生异常", e);
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}

	public static void main(String args[]) {
		System.out.println(12);
	}
	
	/** 
     * post请求并得到返回结果 
     * @param requestUrl 
     * @param requestMethod 
     * @param output 
     * @return 
     */  
    public static String httpsRequest(String requestUrl, String requestMethod, String output) {  
        try{  
            URL url = new URL(requestUrl);  
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setUseCaches(false);  
            connection.setRequestMethod(requestMethod);  
            if (null != output) {  
                OutputStream outputStream = connection.getOutputStream();  
                outputStream.write(output.getBytes("UTF-8"));  
                outputStream.close();  
            }  
            // 从输入流读取返回内容  
            InputStream inputStream = connection.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
            String str = null;  
            StringBuffer buffer = new StringBuffer();  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            inputStream.close();  
            inputStream = null;  
            connection.disconnect();  
            return buffer.toString();  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
  
        return "";  
    }  
}